package com.wanfajie.smsdistribute.db.bean.sms

import android.app.Activity
import com.j256.ormlite.dao.ForeignCollection
import com.j256.ormlite.field.DatabaseField
import com.j256.ormlite.field.ForeignCollectionField
import com.j256.ormlite.table.DatabaseTable
import com.wanfajie.smsdistribute.config.TABLE_SMS

@DatabaseTable(tableName = TABLE_SMS)
data class SmsBean constructor(
        @DatabaseField(columnName = FIELD_ID, generatedId = true)
        val id: Int = 0,

        @DatabaseField(columnName = FIELD_SENDTO)
        val sendTo: String = "",

        @DatabaseField(columnName = FIELD_MESSAGE)
        val message: String = "",

        @DatabaseField(columnName = FIELD_SUBID, defaultValue = "-1")
        val subIndex: Int = -1,

        @DatabaseField(columnName = FIELD_PARTS)
        val partCount: Int = 0
) {

    @DatabaseField(columnName = FIELD_TS)
    val timestamp: Long = System.currentTimeMillis()

    @DatabaseField(columnName = FIELD_COMPLETE)
    var _complete: Boolean = false

    val isComplete: Boolean get() {
        _complete = parts?.size ?: 0 >= partCount
        return _complete
    }

    val isSuccess: Boolean get() {
        return isComplete && parts?.all { it.resultCode == Activity.RESULT_OK } ?: false
    }

    @ForeignCollectionField(eager = false)
    val parts: ForeignCollection<SmsPartBean>? = null

    companion object {
        const val FIELD_ID = "id"
        const val FIELD_SENDTO = "send_to_tel"
        const val FIELD_MESSAGE = "sent_message"
        const val FIELD_TS = "insert_timestamp"
        const val FIELD_PARTS = "total_parts"
        const val FIELD_SUBID = "sub_id"
        const val FIELD_COMPLETE = "is_complete"

        const val TABLE_NAME = TABLE_SMS
    }
}